package com.dd.logistics.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.logistics.common.Result;
import com.dd.logistics.entity.Inventory;
import com.dd.logistics.entity.Supplier;
import com.dd.logistics.entity.SupplierProduct;
import com.dd.logistics.service.InventoryService;
import com.dd.logistics.service.SupplierProductService;
import com.dd.logistics.service.SupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/supplier-product")
@Slf4j
public class SupplierProductController {
    
    @Autowired
    private SupplierProductService supplierProductService;
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private InventoryService inventoryService;
    
    @GetMapping("/{id}")
    public Result<SupplierProduct> getById(@PathVariable Long id) {
        try {
            log.info("查询商品详情，商品ID：{}", id);
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            
            SupplierProduct product = supplierProductService.getById(id);
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            log.info("查询商品详情成功");
            return Result.success(product);
        } catch (Exception e) {
            log.error("查询商品详情失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/list/{supplierId}")
    public Result<List<SupplierProduct>> getProductsBySupplierId(@PathVariable Long supplierId) {
        try {
            log.info("查询供应商商品列表，供应商ID：{}", supplierId);
            if (supplierId == null) {
                return Result.error("供应商ID不能为空");
            }
            
            List<SupplierProduct> list = supplierProductService.getProductsBySupplierId(supplierId);
            log.info("查询供应商商品列表成功，数量：{}", list.size());
            return Result.success(list);
        } catch (Exception e) {
            log.error("查询供应商商品列表失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/page")
    public Result<Page<SupplierProduct>> page(
            @RequestParam Long supplierId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String productName) {
        try {
            log.info("分页查询供应商商品，供应商ID：{}，页码：{}，每页条数：{}，商品名称：{}", 
                    supplierId, current, size, productName);
            
            validatePageParams(supplierId, current, size);
            
            Page<SupplierProduct> page = supplierProductService.getProductsPage(supplierId, current, size, productName);
            log.info("分页查询供应商商品成功，总记录数：{}", page.getTotal());
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询供应商商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PostMapping("/add")
    public Result<Boolean> addProduct(@RequestBody SupplierProduct product) {
        try {
            log.info("添加商���，商品信息：{}", product);
            validateProduct(product, false);
            trimProduct(product);
            
            boolean success = supplierProductService.addProduct(product);
            if (success) {
                Inventory inventory = new Inventory();
                inventory.setSupplierId(product.getSupplierId());
                inventory.setProductId(product.getId());
                inventory.setQuantity(0);
                inventory.setWarningThreshold(0);
                inventoryService.save(inventory);
                
                log.info("添加商品成功，商品ID：{}", product.getId());
                return Result.success("添加商品成功", true);
            } else {
                log.error("添加商品失败");
                return Result.error("添加商品失败");
            }
        } catch (Exception e) {
            log.error("添加商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping("/update")
    public Result<Boolean> updateProduct(@RequestBody SupplierProduct product) {
        try {
            log.info("更新商品，商品信息：{}", product);
            validateProduct(product, true);
            trimProduct(product);
            
            boolean success = supplierProductService.updateProduct(product);
            if (success) {
                log.info("更新商品成功，商品ID：{}", product.getId());
                return Result.success("更新商品成功", true);
            } else {
                log.error("更新商品失败");
                return Result.error("更新商品失败");
            }
        } catch (Exception e) {
            log.error("更新商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping("/status/{id}")
    public Result<Boolean> updateStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        try {
            log.info("更新商品状态，商品ID：{}，状态：{}", id, status);
            
            // 参数校验
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            if (status == null) {
                return Result.error("状态值不能为空");
            }
            if (status != SupplierProduct.STATUS_ENABLED && status != SupplierProduct.STATUS_DISABLED) {
                return Result.error("无效的状态值");
            }
            
            boolean success = supplierProductService.updateStatus(id, status);
            String statusName = status == SupplierProduct.STATUS_ENABLED ? "启用" : "禁用";
            return success ? Result.success("商品" + statusName + "成功", true) : Result.error("商品" + statusName + "失败");
        } catch (Exception e) {
            log.error("更新商品状态失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping("/enable/{id}")
    public Result<Boolean> enableProduct(@PathVariable Long id) {
        try {
            log.info("启用商品，商品ID：{}", id);
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            
            boolean success = supplierProductService.updateStatus(id, SupplierProduct.STATUS_ENABLED);
            return success ? Result.success("商品启用成功", true) : Result.error("商品启用失败");
        } catch (Exception e) {
            log.error("启用商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping("/disable/{id}")
    public Result<Boolean> disableProduct(@PathVariable Long id) {
        try {
            log.info("禁用商品，商品ID：{}", id);
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            
            boolean success = supplierProductService.updateStatus(id, SupplierProduct.STATUS_DISABLED);
            return success ? Result.success("商品禁用成功", true) : Result.error("商品禁用失败");
        } catch (Exception e) {
            log.error("禁用商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping("/batch-enable")
    public Result<Map<String, Integer>> batchEnable(@RequestBody List<Long> ids) {
        try {
            log.info("批量启用商品，商品IDs：{}", ids);
            if (ids == null || ids.isEmpty()) {
                return Result.error("商品ID列表不能为空");
            }
            
            Map<String, Integer> result = supplierProductService.batchUpdateStatus(ids, SupplierProduct.STATUS_ENABLED);
            int successCount = result.get("success");
            int failCount = result.get("fail");
            
            if (failCount == 0) {
                return Result.success("所有商品启用成功", result);
            } else if (successCount > 0) {
                return Result.success(String.format("部分商品启用成功，成功%d个，失败%d个", 
                    successCount, failCount), result);
            } else {
                return Result.error("所有商品启用失败");
            }
        } catch (Exception e) {
            log.error("批量启用商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @PutMapping("/batch-disable")
    public Result<Map<String, Integer>> batchDisable(@RequestBody List<Long> ids) {
        try {
            log.info("批量禁用商品，商品IDs：{}", ids);
            if (ids == null || ids.isEmpty()) {
                return Result.error("商品ID列表不能为空");
            }
            
            Map<String, Integer> result = supplierProductService.batchUpdateStatus(ids, SupplierProduct.STATUS_DISABLED);
            int successCount = result.get("success");
            int failCount = result.get("fail");
            
            if (failCount == 0) {
                return Result.success("所有商品禁用成功", result);
            } else if (successCount > 0) {
                return Result.success(String.format("部分商品禁用成功，成功%d个，失败%d个", 
                    successCount, failCount), result);
            } else {
                return Result.error("所有商品禁用失败");
            }
        } catch (Exception e) {
            log.error("批量禁用商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/status-count/{supplierId}")
    public Result<Map<String, Integer>> getStatusCount(@PathVariable Long supplierId) {
        try {
            log.info("查询供应商商品状态统计，供应商ID：{}", supplierId);
            if (supplierId == null) {
                return Result.error("供应商ID不能为空");
            }
            
            Map<String, Integer> result = supplierProductService.getStatusCount(supplierId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询供应商商品状态统计失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @DeleteMapping("/batch")
    public Result<Map<String, Object>> batchDelete(@RequestBody List<Long> ids) {
        try {
            log.info("批量删除商品，商品IDs：{}", ids);
            if (ids == null || ids.isEmpty()) {
                return Result.error("商品ID列表不能为空");
            }
            
            Map<String, Object> result = supplierProductService.batchDelete(ids);
            int successCount = (Integer) result.get("success");
            int failCount = (Integer) result.get("fail");
            
            if (failCount == 0) {
                return Result.success("所有商品删除成功", result);
            } else if (successCount > 0) {
                return Result.success(String.format("部分商品删除成功，成功%d个，失败%d个", 
                    successCount, failCount), result);
            } else {
                return Result.error("所有商品删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/search")
    public Result<Page<SupplierProduct>> search(
            @RequestParam(required = false) Long supplierId,
            @RequestParam(required = false) String productCode,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            log.info("搜索商品，供应商ID：{}，商品编码：{}，商品名称：{}，状态：{}，页码：{}，每页条数：{}", 
                    supplierId, productCode, productName, status, current, size);
            
            if (current < 1) {
                return Result.error("页码必须大于0");
            }
            if (size < 1) {
                return Result.error("每页条数必须大于0");
            }
            
            Page<SupplierProduct> page = supplierProductService.search(supplierId, productCode, 
                productName, status, current, size);
            return Result.success(page);
        } catch (Exception e) {
            log.error("搜索商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/detail/{id}")
    public Result<Map<String, Object>> getDetail(@PathVariable Long id) {
        try {
            log.info("查询商品详情，商品ID：{}", id);
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            
            // 使用关联查询获取���品信息
            SupplierProduct product = supplierProductService.getProductDetail(id);
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            // 查询供应商信息
            Supplier supplier = supplierService.getById(product.getSupplierId());
            
            Map<String, Object> result = new HashMap<>();
            // 商品基本信息
            result.put("id", product.getId());
            result.put("supplierId", product.getSupplierId());
            result.put("productCode", product.getProductCode());
            result.put("price", product.getPrice());
            result.put("specification", product.getSpecification());
            result.put("unit", product.getUnit());
            result.put("remark", product.getRemark());
            result.put("status", product.getStatus());
            result.put("statusName", product.getStatusName());
            result.put("createTime", product.getCreateTime());
            result.put("updateTime", product.getUpdateTime());
            
            // 商品关联信息
            result.put("productInfo", new HashMap<String, Object>() {{
                put("name", product.getProductName());
                put("specification", product.getProductSpecification());
                put("unit", product.getProductUnit());
                put("price", product.getProductPrice());
            }});
            
            // 供应商信息
            if (supplier != null) {
                result.put("supplier", new HashMap<String, Object>() {{
                    put("id", supplier.getId());
                    put("name", supplier.getName());
                    put("contact", supplier.getContact());
                    put("phone", supplier.getPhone());
                }});
            }
            
            log.info("查询商品详情成功");
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询商品详情失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteProduct(@PathVariable Long id) {
        try {
            log.info("删除商品，商品ID：{}", id);
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            
            // 检查是否库存
            QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
            wrapper.eq("product_id", id);
            Inventory inventory = inventoryService.getOne(wrapper);
            if (inventory != null && inventory.getQuantity() > 0) {
                return Result.error("商品还有库存，不能删除");
            }
            
            boolean success = supplierProductService.removeById(id);
            if (success && inventory != null) {
                // 同时删除库存记录
                inventoryService.removeById(inventory.getId());
            }
            return success ? Result.success("删除商品成功", true) : Result.error("删除商品失败");
        } catch (Exception e) {
            log.error("删除商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/stock-info/{id}")
    public Result<Map<String, Object>> getStockInfo(@PathVariable Long id) {
        try {
            log.info("查询商品库存信息，商品ID：{}", id);
            if (id == null) {
                return Result.error("商品ID不能为空");
            }
            
            SupplierProduct product = supplierProductService.getById(id);
            if (product == null) {
                return Result.error("商品不存在");
            }
            
            QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
            wrapper.eq("product_id", id);
            Inventory inventory = inventoryService.getOne(wrapper);
            
            Map<String, Object> result = new HashMap<>();
            result.put("product", product);
            result.put("inventory", inventory != null ? inventory : new Inventory());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询商品库存信息失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/low-stock")
    public Result<List<Map<String, Object>>> getLowStockProducts() {
        try {
            log.info("查询低库存商品列表");
            List<SupplierProduct> products = supplierProductService.list();
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (SupplierProduct product : products) {
                QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
                wrapper.eq("product_id", product.getId());
                Inventory inventory = inventoryService.getOne(wrapper);
                
                if (inventory != null && inventory.getQuantity() <= inventory.getWarningThreshold()) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("product", product);
                    item.put("inventory", inventory);
                    result.add(item);
                }
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询低库存商品失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    @GetMapping("/stock-warning/{supplierId}")
    public Result<Map<String, Integer>> getStockWarning(@PathVariable Long supplierId) {
        try {
            log.info("查询供应商库存预警信息，供应商ID：{}", supplierId);
            if (supplierId == null) {
                return Result.error("供应商ID不能为空");
            }
            
            QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
            wrapper.eq("supplier_id", supplierId);
            
            // 统计总商品数
            long total = inventoryService.count(wrapper);
            
            // 统计低库存商品数
            wrapper.clear();
            wrapper.eq("supplier_id", supplierId)
                   .apply("quantity <= warning_threshold");
            long lowStock = inventoryService.count(wrapper);
            
            // 统计零库存商品数
            wrapper.clear();
            wrapper.eq("supplier_id", supplierId)
                   .eq("quantity", 0);
            long zeroStock = inventoryService.count(wrapper);
            
            Map<String, Integer> result = new HashMap<>();
            result.put("total", (int)total);
            result.put("lowStock", (int)lowStock);
            result.put("zeroStock", (int)zeroStock);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询供应商库存预警信息失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 校验分页参数
     */
    private void validatePageParams(Long supplierId, Integer current, Integer size) {
        if (supplierId == null) {
            throw new RuntimeException("供应商ID不能为空");
        }
        if (current == null || current < 1) {
            throw new RuntimeException("页码必须大于0");
        }
        if (size == null || size < 1) {
            throw new RuntimeException("每页条数必须大于0");
        }
        if (size > 100) {
            throw new RuntimeException("每页条数不能超过100");
        }
    }
    
    /**
     * 校验商品信息
     */
    private void validateProduct(SupplierProduct product, boolean isUpdate) {
        if (product == null) {
            throw new RuntimeException("商品信息不能为空");
        }
        if (isUpdate && product.getId() == null) {
            throw new RuntimeException("商品ID不能为空");
        }
        if (!isUpdate && product.getSupplierId() == null) {
            throw new RuntimeException("供应商ID不能为空");
        }
        if (product.getProductCode() == null || product.getProductCode().trim().isEmpty()) {
            throw new RuntimeException("商品编码不能为空");
        }
        if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
            throw new RuntimeException("商品名称不能为空");
        }
        if (product.getPrice() == null) {
            throw new RuntimeException("商品价格不能为空");
        }
        if (product.getUnit() == null || product.getUnit().trim().isEmpty()) {
            throw new RuntimeException("商品单位不能为空");
        }
        if (product.getPrice() != null && product.getPrice().compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("商品价格不能小于0");
        }
        
        // 如果是更新操作，检查库存
        if (isUpdate) {
            QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
            wrapper.eq("product_id", product.getId());
            Inventory inventory = inventoryService.getOne(wrapper);
            
            // 如果商品已禁用且有库存，不允许更新
            if (product.getStatus() != null 
                && product.getStatus().equals(SupplierProduct.STATUS_DISABLED)
                && inventory != null 
                && inventory.getQuantity() > 0) {
                throw new RuntimeException("商品还有库存，不能禁用");
            }
        }
    }
    
    /**
     * 处理字符串字段，去除两端空格
     */
    private void trimProduct(SupplierProduct product) {
        product.setProductCode(product.getProductCode().trim());
        product.setProductName(product.getProductName().trim());
        if (product.getSpecification() != null) {
            product.setSpecification(product.getSpecification().trim());
        }
        if (product.getUnit() != null) {
            product.setUnit(product.getUnit().trim());
        }
        if (product.getRemark() != null) {
            product.setRemark(product.getRemark().trim());
        }
    }
} 